#include "head.hpp"


void read_fifo(int fd)
{
    char buffer[SIZE];
    while(true)
    {
        memset(buffer, '\0', SIZE);
        ssize_t sz = read(fd, buffer, SIZE - 1);
        if(sz > 0)
        {
            buffer[sz] = '\0';
            cout << "server[" << getpid() << "]:" << buffer << endl;
        }
        else if(sz == 0)
        {
            break;
        }

    }
}

int main()
{
    int ret = mkfifo(ipcPath.c_str(), MODE);
    if(ret == -1)
    {
        perror("mkfifo");
        exit(1);
    }
    log("创建命名管道成功", Debug) << "step 1" << endl;
    int fd = open(ipcPath.c_str(), O_RDONLY);
    if(fd < 0)
    {
        perror("open");
        exit(2);
    }
    log("以读方式打开管道成功", Debug) << "step 2" << endl;
    for(int i = 0; i < 3; ++i)
    {
        int _fd = fork();
        if(_fd < 0)
        {
            perror("fork");
            exit(3);
        }
        if(_fd == 0)
        {
            //child
            read_fifo(fd);
            exit(1);
        }
        
    }
    for(int i = 0; i < 3; ++i)
    {
        pid_t ret = waitpid(-1, nullptr, 0);
        if(ret > 0)
        {
            string str = "等到子进程:";
            string id = to_string(ret);
            log(str+id, Notice);
        }
    }   
    close(fd);
    log("关闭打开的管道", Debug) << "step 3" << endl;
    unlink(ipcPath.c_str());
    log("删除管道文件成功", Debug) << "step 4" << endl;
    return 0;
}